﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;

namespace mijiaxueche.weixin.help
{
    public class wxGetAccessToken
    {
        /// <summary>
        /// 缓存处理的获取accessToken的方法
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public static String getAccessToken()
        {
            object accessToken = CacheAccess.GetFromCache("accessToken");
            if (accessToken == null || accessToken.ToString() == "")
            {
                accessToken = GetAccessTokenByWx();
                CacheAccess.SaveToCache("accessToken", accessToken, 600000);
            }
            return accessToken.ToString();
        }

        /// <summary>
        /// 获取Ticket
        /// </summary>
        /// <returns></returns>
        public static string getTicket()
        {
            object jsonStr = CacheAccess.GetFromCache("jsapi_ticket");
            if (jsonStr == null || jsonStr.ToString() == "")
            {
                jsonStr = GetApi_ticketByWX();
                CacheAccess.SaveToCache("jsapi_ticket", jsonStr, 600000);
            }
            return jsonStr.ToString();
        }

        private static string GetAccessTokenByWx()
        {

            string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", wxHelper.appid, wxHelper.secret);
            string json = GetTextByUrl.GetGZipEncodedHTMLContent(url, "");
            //{"access_token":"ACCESS_TOKEN","expires_in":7200}
            JObject ja = (JObject)JsonConvert.DeserializeObject(json);
            string access_token = ja["access_token"].ToString();
            return access_token;
        }

        private static string GetApi_ticketByWX()
        {
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", getAccessToken());
            string json = GetTextByUrl.GetGZipEncodedHTMLContent(url, "");
            //{
            //"errcode":0,
            //"errmsg":"ok",
            //"ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",
            //"expires_in":7200


            JObject ja = (JObject)JsonConvert.DeserializeObject(json);
            if (ja["errcode"].ToString() != "0")
            {
                CacheAccess.RemoveCache("accessToken");
                CacheAccess.RemoveCache("jsapi_ticket");
                return GetApi_ticketByWX();
            }
            string access_token = ja["ticket"].ToString();
            return access_token;
        }

    }
}